package com.xyh.transaction.controller;

import com.alibaba.fastjson.JSONObject;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.xyh.transaction.common.ImageType;
import com.xyh.transaction.config.IgnoreUrlsConfig;
import com.xyh.transaction.entity.Category;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.Image;
import com.xyh.transaction.mapper.CategoryMapper;
import com.xyh.transaction.mapper.GoodsMapper;
import com.xyh.transaction.mapper.ImageMapper;
import com.xyh.transaction.schedule.DeleteExpiredImageScheduler;
import com.xyh.transaction.schedule.GoodsMeilisearchScheduler;
import com.xyh.transaction.utils.EmailUtil;
import com.xyh.transaction.utils.ImageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "测试接口管理")
@RequestMapping("/test")
public class TestController {

    @Autowired
    private GoodsMeilisearchScheduler goodsMeilisearchScheduler;

    @ApiOperation(value = "测试商品同步到 Meilisearch")
    @GetMapping("/goods")
    public String testGoods() {
        try {
            goodsMeilisearchScheduler.addGoodsToMeilisearch();
        } catch (MeilisearchException e) {
            throw new RuntimeException(e);
        }

        return "success";
    }

    @Autowired
    private DeleteExpiredImageScheduler deleteExpiredImageScheduler;

    @ApiOperation(value = "测试删除过期图片")
    @GetMapping("/delete")
    public String testDelete() {
        deleteExpiredImageScheduler.clearExpiredImages();
        return "success";
    }

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Value("${image.localDir}")
    private String localDirectory;

    @ApiOperation(value = "测试添加商品图片")
    @GetMapping("/add/goods/image")
    public String testAddImage() {
        // 获取所有分类
        List<Category> categoryList = new ArrayList<>(categoryMapper.findAll(new Category()));

        // 遍历每个分类
        for (Category category : categoryList) {
            String categoryName = category.getName();
            log.info("开始处理分类：{}", categoryName);
            long start = System.currentTimeMillis();

            // 计算当前分类和其下商品所需的图片数量
            // 每个分类需要1张图片
            int imagesNeeded = 1;

            // 获取该分类下的所有商品
            Goods goods = new Goods();
            goods.setCategoryId(category.getId());
            List<Goods> goodsList = goodsMapper.findAll(goods);
            // 每个商品最多需要3张图片
            imagesNeeded += goodsList.size() * 3;
            log.info("当前分类需要{}张图片", imagesNeeded);

            // 下载足够的图片
            categoryName = "女装".equals(categoryName) ? "女 服装" : categoryName;
            categoryName = "男装".equals(categoryName) ? "男 服装" : categoryName;
            categoryName = "包包".equals(categoryName) ? "包 背包 挎包" : categoryName;
            List<String> allImageUrls = ImageUtils.downloadLargeImages(categoryName, localDirectory, imagesNeeded);
            if (allImageUrls.size() < imagesNeeded) {
                log.error("分类 {} 的图片数量不足，期望 {} 张，实际只有 {} 张", categoryName, imagesNeeded, allImageUrls.size());
                continue;
            }

            int imageIndex = 0;

            // 保存分类图片
            if (imageMapper.findByRelatedId(category.getId(), ImageType.CATEGORY).isEmpty()) {
                mappingCategoryImage(allImageUrls.get(imageIndex++), categoryName, category.getId());
            }

            // 为每个商品分配图片，最多分配3张
            for (Goods good : goodsList) {
                if (!imageMapper.findByRelatedId(good.getId(), ImageType.GOODS).isEmpty()) {
                    continue;
                }
                // 确保图片数量不超过3张且不越界
                int imageCount = Math.min(3, allImageUrls.size() - imageIndex);
                for (int j = 0; j < imageCount; j++) {
                    mappingGoodsImage(allImageUrls.get(imageIndex++), good.getName(), good.getId());
                }
            }
            log.info("处理分类 {} 完成，耗时：{} ms", categoryName, System.currentTimeMillis() - start);
        }

        return "success";
    }


    private void mappingGoodsImage(String url, String goodsName, Integer goodsId) {
        // 把图片保存进t_image
        Image image = new Image();
        image.setAltText(goodsName);
        image.setUrl(ImageUtils.getFileNameFromUrl(url));
        image.setRelatedId(goodsId);
        image.setImageType(ImageType.GOODS);
        image.setCreateTime(LocalDateTime.now());
        image.setUpdateTime(LocalDateTime.now());
        imageMapper.insert(image);
    }

    private void mappingCategoryImage(String url, String categoryName, Integer categoryId) {
        // 把图片保存进t_image
        Image image = new Image();
        image.setAltText(categoryName);
        image.setUrl(ImageUtils.getFileNameFromUrl(url));
        image.setRelatedId(categoryId);
        image.setImageType(ImageType.CATEGORY);
        image.setCreateTime(LocalDateTime.now());
        image.setUpdateTime(LocalDateTime.now());
        imageMapper.insert(image);
    }

    private void mappingRotateImage(String url, String rotateName, Integer rotateId) {
        // 把图片保存进t_image
        Image image = new Image();
        image.setAltText(rotateName);
        image.setUrl(ImageUtils.getFileNameFromUrl(url));
        image.setRelatedId(rotateId);
        image.setImageType(ImageType.CATEGORY);
        image.setCreateTime(LocalDateTime.now());
        image.setUpdateTime(LocalDateTime.now());
        imageMapper.insert(image);
    }


    public static String translate(String text) {
        try {
            String urlStr = "https://api.mymemory.translated.net/get?q=" + text + "&langpair=zh|en";
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 使用 Fastjson 解析 JSON
            JSONObject jsonObject = JSONObject.parseObject(response.toString());

            return jsonObject.getJSONObject("responseData").getString("translatedText");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("翻译失败：{}", e.getMessage(),e);
            return null;
        }
    }

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @ApiOperation(value = "测试忽略 URL")
    @GetMapping("/ignore/urls")
    public String testIgnoreUrls() {
        ArrayList<String> res = new ArrayList<>();
        res.addAll(ignoreUrlsConfig.getAnonymous());
        res.addAll(ignoreUrlsConfig.getPermitAll());
        res.addAll(ignoreUrlsConfig.getSpecial());
        return JSONObject.toJSONString(res);
    }

    @Autowired
    private EmailUtil emailUtil;

    @ApiOperation(value = "测试发送邮件")
    @GetMapping("/send/email")
    public String testSendEmail() {
        try {
            emailUtil.sendExceptionToAdmin(new RuntimeException("测试异常"));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送邮件失败：{}", e.getMessage(), e);
            return "fail";
        }
        return "success";
    }
}
